/*
 *所有关于tb_project_billing_allocation类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*tb_project_billing_allocationService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using MYData.Core.BaseProvider;
using MYData.Core.Extensions.AutofacManager;
using MYData.Entity.DomainModels;
using System.Linq;
using MYData.Core.Utilities;
using System.Linq.Expressions;
using MYData.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using MYData.System.IRepositories;
using System.Threading.Tasks;
using System;
using MYData.Core.ManageUser;
using MYData.Core.EFDbContext;
using MYData.Entity.DomainModels.ApiEntity.Input;
using Mapster;
using Newtonsoft.Json;

namespace MYData.System.Services
{
    public partial class tb_project_billing_allocationService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Itb_project_billing_allocationRepository _repository;//访问数据库
        private readonly Itb_project_workflowtableRepository _workRepository;
        private readonly VOLContext _db;

        [ActivatorUtilitiesConstructor]
        public tb_project_billing_allocationService(
            Itb_project_billing_allocationRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            Itb_project_workflowtableRepository workRepository,
            VOLContext db
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _workRepository = workRepository;
            _db = db;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        WebResponseContent webResponse = new WebResponseContent();
        UserInfo userInfo = UserContext.Current.UserInfo;
        /// <summary>
        /// 经费下拨明细列表(项目基础信息表+入账单表+流程表)
        /// 名称模糊查询
        /// </summary>
        /// <returns></returns>
        //异步方法使你的程序可以在执行一个可能长期运行的任务的同时继续对其他事件做出反应而不必等待任务完成
        public async Task<WebResponseContent> GetAllocation(string id)
        {
            //LINQ查询用于连接数据库中的tb_project_billing_allocation和tb_project_apply_basicinfo表tb_project_billing
            var list = from x in _db.Set<tb_project_billing_allocation>().Where(x => x.billingId == id).ToList()
                       join y in _db.Set<tb_project_baseinfo>() on x.projectId equals y.projectId
                       join z in _db.Set<tb_project_billing>() on x.billingId equals z.billingId
                       //'isDel'属性为0(意味着条目没有被删除)的两个表中选择特定的属性。
                       select new
                       {
                           x.allocationId,
                           x.billingId,
                           x.projectId,
                           x.belowflowId,
                           y.projectMoney,//项目总经费
                           y.projectName,//项目名称
                           y.projectScoreunit,//来源单位
                           y.projectPerson,//负责人
                           z.billingTime,//财务到账时间,
                           x.allocationExpenditure,//本次下拨
                           accounting = List(x.projectId),//已到账总经费
                           progress = tb_project_workflowstepService.Instance.GetProgress(x.allocationId, "tb_project_billing_allocation"),
                           operate = tb_project_workflowstepService.Instance.GetOperate(x.allocationId, "tb_project_billing_allocation") == null ? "" : JsonConvert.SerializeObject(tb_project_workflowstepService.Instance.GetOperate(x.allocationId, "tb_project_billing_allocation"))
                       };
            //结果集作为匿名对象返回
            return webResponse.OK("显示成功", list);
        }
        

        /// <summary>
        /// 计算已到账总经费
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        /// 通过汇总分配支出值来计算
        public decimal List(string projectId)
        {
            //来自给定项目的tb_project_billing_allocation表
            //将变量初始化为0
            decimal accounting = 0;
            //查询所有条目的tb_project_billing_allocation表
            var billinglist = from b in _db.Set<tb_project_billing_allocation>()
                                  //给定的投射体和isDelete设置为0(未删除)
                              where b.isDelete == 0 && b.projectId == projectId
                              select new
                              {
                                  //只选择allocationExpenditure值
                                  b.allocationExpenditure,
                              };
            billinglist.ToList().ForEach(billing =>
            {
                //并将分配支出值添加到变量中
                accounting += billing.allocationExpenditure;
            });
            ////返回最终的值
            return accounting;
        }

        /// <summary>
        /// 根据基础信息主键显示经费下拨表详情信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// WJQ 2023/4/11
        public async Task<WebResponseContent> basicBillingDetail(string id)
        {
            var list = from x in _db.Set<tb_project_billing_allocation>().Where(x => x.projectId == id).ToList()
                       join y in _db.Set<tb_project_billing>() on x.billingId equals y.billingId
                       join z in _db.Set<tb_project_apply_basicinfo>() on x.projectId equals z.projectID
                       where x.isDelete == 0 && y.isDelete == 0 && z.isDelete == 0
                       select new
                       {
                           billingTime = y.billingTime.ToString("yyyy-MM-dd"),                    //到账时间
                           accounting = List(x.projectId).ToString(),//已到账总经费
                           expenditureMoney = Math.Round(z.expenditureMoney, 4).ToString(),      //总经费
                           NotMoney = 0                                                          //未下拨经费
                       };

            return webResponse.OK("显示成功", list);
        }
        /// <summary>
        /// 经费分配详情信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// WJQ 2023/4/11
        public async Task<WebResponseContent> billingAllocationDetail(string id)
        {
            var list = from x in _db.Set<tb_project_billing_allocation>().Where(x => x.allocationId == id).ToList()
                       join y in _db.Set<tb_project_billing>() on x.billingId equals y.billingId
                       join z in _db.Set<tb_project_baseinfo>() on x.projectId equals z.projectId
                       where x.isDelete == 0 && y.isDelete == 0 
                       select new
                       {
                           billingTime = y.billingTime.ToString("yyyy-MM-dd"),                       //到账时间
                           accounting = List(x.projectId).ToString(),                               //已到账总经费
                           expenditureMoney = z.projectMoney,                                       //总经费
                           NotMoney = 0,                                                            //未下拨经费
                           billingUnit=y.billingUnit,
                           DaoMoney=x.UpdirectMoney+x.UpindirectMoney,
                           billingBank=y.billingBank,
                           allocationId=x.allocationId,
                       };

            return webResponse.OK("显示成功", list);
        }
        /// <summary>
        /// 经费分配(添加)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// WJQ 2023/4/14
        public async Task<WebResponseContent> basicBillingAdd(basicallocationInput_Dto inputdto)
        {
            //定义一个雪花id
            string allocationId = new Snowflake.Core.IdWorker(1, 1).NextId().ToString();
            // 将输入Dto转换为领域模型
            // 把输入DTO转换成tb_project_billing_allocation实体
            var model = inputdto.Adapt<tb_project_billing_allocation>();
            model.allocationId = allocationId;
            //流程关系表添加
            tb_project_workflowtable workflowtable = new tb_project_workflowtable();
            //查询流程表中是否有这个表
            var workFlow = _db.Set<Sys_WorkFlow>().Where(x => x.WorkTable == "tb_project_billing_allocation").FirstOrDefault();
            workflowtable.workFlowId = workFlow.WorkFlow_Id;
            workflowtable.workName = workFlow.WorkName;
            workflowtable.projectTableKey = allocationId;
            workflowtable.projectTable = workFlow.WorkTable;
            workflowtable.workTableName = workFlow.WorkTableName;
            workflowtable.currentOrderId = "1";//审批节点
            workflowtable.auditStatus = 0;//0默认为审核中
            workflowtable.createDate = DateTime.Now;
            workflowtable.creator = userInfo.UserName;
            // 添加基本信息到数据库
            _repository.Add(model);
            //流程关系表添加
            _workRepository.Add(workflowtable, false);
            await _repository.SaveChangesAsync();
            //返回
            return webResponse.OK("添加成功");
        }

        private class dto
        {

            public string? id { get; set; }
            public string? name { get; set; }
            public string? type { get; set; }
            public string? left { get; set; }
            public string? top { get; set; }
            public string? ico { get; set; }
            public string? state { get; set; }
            public string? stepValue { get; set; }
            public string? nodeType { get; set; }
            public string? userId { get; set; }
            public string? roleId { get; set; }
            public string? deptId { get; set; }

        }
    }
}

